import { computed, reactive, toRef, inject } from "vue"
import { piniaSymbol } from './rootStore'

export default (name, option) => {
    const { state, getters, actions } = option

    const store = {}

    if (state && typeof state === 'function') {

        const _state = state()
        store.$state = reactive(_state)

        for (const key in _state) {
            //tips:_state只是普通对象，转换后store里的值与_state不形成关系，
            // filter，nextId，todos[]
            store[key] = toRef(store.$state, key)
            // store[key] = toRef(_state, key)
        }

    }

    if (getters && Object.keys(getters).length > 0) {
        for (const key in getters) {
            store[key] = computed(getters[key].bind(store.$state, store.$state))
            store.$state[key] = store[key]
        }
    }

    if (actions && Object.keys(actions).length > 0) {
        Object.assign(store, actions)
    }

    return () => {
        const setSubStore = inject(piniaSymbol)
        const piniaStore = setSubStore(name, reactive(store))
        return piniaStore[name]
    }
}